package com.basic.hellorabbit.controller;

import com.basic.hellorabbit.entity.ExcelDatas;
import com.basic.hellorabbit.entity.Teacher;
import com.basic.hellorabbit.util.ExcelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* @Description:    Excel测试页面
* @Author:         Joe
* @CreateDate:     2020/3/20 17:15
*/
@Controller
public class ExcelController {

    /**
     * 跳转到Excel测试页面
     * @return
     */
    @RequestMapping(value = "/toexcel",method = RequestMethod.GET)
    public String toExcel(){
        return "excel";
    }

    /**
     * 数据导出
     * @param response
     */
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public void ExportExcel(HttpServletResponse response){
        List<Teacher> teachers = new ArrayList<>();
        teachers.add(new Teacher(1,"韩信",25,"男","刺客"));
        teachers.add(new Teacher(1,"钟无艳",25,"女","战士"));
        ExcelDatas excelDatas = new ExcelDatas();
        excelDatas.setFileName("teachers.xlsx");
        String[] strings = {"id","姓名","年纪","性别","科目"};
        excelDatas.setHead(strings);
        excelDatas.setDatas(teachers);
        ExcelUtil.exportExcel(response,excelDatas);
    }
    /**
     * 数据导入
     * @param file
     */
    @ResponseBody
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public String importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String fileName = file.getName();
        List<Object[]> list = ExcelUtil.importExcel(inputStream,fileName);
        for (int i = 0; i < list.size(); i++) {
            Teacher teacher = new Teacher();
            teacher.setId((Integer)list.get(i)[0]);
            teacher.setName((String) list.get(i)[1]);
            teacher.setAge((Integer)list.get(i)[2]);
            teacher.setSex((String)list.get(i)[3]);
            teacher.setSubject((String) list.get(i)[4]);
            System.out.println(teacher.toString());
        }
        return "导入成功！";
    }
}
